package org.elepower.utils;

import org.elepower.controller.Constants;
import org.elepower.pojo.PsFunction;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 权限拦截器：判断用户是否访问了自己不能访问的资源
 */
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        Object user = session.getAttribute(Constants.LOGIN_USER);

        if (user == null){
            return true;
        }
        //  /hello/sysUser/logout
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();

        String path = uri.replaceFirst(contextPath+"/","");

        //去session中取出用户的权限列表结合，判断这个地址是否在里面就可以了
        List<PsFunction> list = (List<PsFunction>) request.getSession().getAttribute(Constants.LOGIN_USER_PERS);
        for (PsFunction per:list) {
            if(per.getFunUrl()!= null && per.getFunUrl().equals(path)){
                return true;
            }
        }
        response.sendRedirect(request.getContextPath() + "/error.jsp");
        return false;
    }
}
